﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace ThoiTrangT2B.Admin
{
    public partial class DangSanPham : System.Web.UI.Page
    {
        private static int IDSanPham;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadListSanPham();
                LoadHangSP(ddlHangSanXuat);
                LoadNhomSP();
                LoadColor();
                MultiView1.ActiveViewIndex = 1;
            }
        }

        private void LoadColor()
        {
            string sql = "SELECT * FROM dbo.tblT2BDanhMuc WHERE MaDM = 'cl'";
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql);
            dtlMauSac.DataSource = dt;
            dtlMauSac.DataBind();
        }

        protected void LoadListSanPham()
        {
            string sql = "SELECT s.Image,d.TenDM AS Hang,s.TenSP,s.MaSP,s.ID,s.Gia,(s.Gia - s.Gia*s.KM/100) AS Giacu,s.KM " +
                         "FROM dbo.tblT2BSanPham s INNER JOIN dbo.tblT2BDanhMuc d ON s.ThuongHieuID_DM = d.ID ORDER BY s.UpdateDate DESC";
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql);
            grvData.DataSource = dt;
            grvData.DataBind();
        }

        protected void LoadListSanPham(int hang)
        {
            string sql = "SELECT s.Image,d.TenDM AS Hang,s.TenSP,s.MaSP,s.ID,s.Gia,(s.Gia - s.Gia*s.KM/100) AS Giacu,s.KM " +
                         "FROM dbo.tblT2BSanPham s INNER JOIN dbo.tblT2BDanhMuc d ON s.ThuongHieuID_DM = d.ID WHERE s.ThuongHieuID_DM = @ThuongHieuID_DM OR @ThuongHieuID_DM = -1 ORDER BY s.UpdateDate DESC";
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@ThuongHieuID_DM", SqlDbType.Int, ParameterDirection.Input, hang));
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql, arrParams);
            grvData.DataSource = dt;
            grvData.DataBind();
        }

        protected void SuaSanPham()
        {
            string sql = "";
            List<SqlParameter> arrParams = new List<SqlParameter>();
            SqlTransaction Mytrans = SqlHelper.BeginTransaction();
            try
            {
                string img = "";
                if (txtAnhSP.HasFile)
                {
                    img += "Image = @Image,";
                    arrParams.Add(SqlHelper.CreateParameterObject("@Image", SqlDbType.NVarChar, ParameterDirection.Input, UploadFile(txtAnhSP)));
                }
                sql = "UPDATE dbo.tblT2BSanPham SET Menu_ID = @Menu_ID, TenSP = @TenSP,MaSP = @MaSP ," + img +
                      "ThuongHieuID_DM = @ThuongHieuID_DM,Gia = @Gia,KM = @KM,IsNew = @IsNew,GhiChu = @GhiChu WHERE ID = @ID";

                arrParams.Add(SqlHelper.CreateParameterObject("@ThuongHieuID_DM", SqlDbType.Int, ParameterDirection.Input, cboHangSanXuat.SelectedValue));
                arrParams.Add(SqlHelper.CreateParameterObject("@Menu_ID", SqlDbType.Int, ParameterDirection.Input, cboMenu.SelectedValue));
                arrParams.Add(SqlHelper.CreateParameterObject("@TenSP", SqlDbType.NVarChar, ParameterDirection.Input, txtTenSP.Text));
                arrParams.Add(SqlHelper.CreateParameterObject("@MaSP", SqlDbType.NVarChar, ParameterDirection.Input, txtMaSP.Text));
                arrParams.Add(SqlHelper.CreateParameterObject("@KM", SqlDbType.Int, ParameterDirection.Input, Convert.ToInt32(txtKhuyenMai.Text.Equals("") ? "0" : txtKhuyenMai.Text)));
                arrParams.Add(SqlHelper.CreateParameterObject("@Gia", SqlDbType.Float, ParameterDirection.Input, Convert.ToDouble(txtGiaSP.Text)));
                arrParams.Add(SqlHelper.CreateParameterObject("@IsNew", SqlDbType.Int, ParameterDirection.Input, rbtNew.Checked ? 1 : 0));
                arrParams.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, IDSanPham));
                arrParams.Add(SqlHelper.CreateParameterObject("@GhiChu", SqlDbType.NText, ParameterDirection.Input, txtGhiChu.Value));
                SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParams);
                ThemAnhSanPham(IDSanPham);
                Mytrans.Commit();
            }
            catch (Exception ex)
            {
                Response.Write(ex.StackTrace);
                Mytrans.Rollback();
            }
        }

        protected void ThemSanPham()
        {
            string sql = "";
            List<SqlParameter> arrParams = new List<SqlParameter>();
            SqlTransaction Mytrans = SqlHelper.BeginTransaction();
            try
            {

                sql = "INSERT INTO dbo.tblT2BSanPham(ThuongHieuID_DM,Menu_ID,TenSP,MaSP,Image,KM,Gia,IsNew,CreateDate,UpdateDate,GhiChu) " +
                      "VALUES  (@ThuongHieuID_DM,@Menu_ID,@TenSP,@MaSP,@Image,@KM,@Gia,@IsNew,GETDATE(),GETDATE(),@GhiChu) " +
                      "SELECT IDENT_CURRENT('tblT2BSanPham')";

                arrParams.Add(SqlHelper.CreateParameterObject("@ThuongHieuID_DM", SqlDbType.Int, ParameterDirection.Input, cboHangSanXuat.SelectedValue));
                arrParams.Add(SqlHelper.CreateParameterObject("@Menu_ID", SqlDbType.Int, ParameterDirection.Input, cboMenu.SelectedValue));
                arrParams.Add(SqlHelper.CreateParameterObject("@TenSP", SqlDbType.NVarChar, ParameterDirection.Input, txtTenSP.Text));
                arrParams.Add(SqlHelper.CreateParameterObject("@MaSP", SqlDbType.NVarChar, ParameterDirection.Input, txtMaSP.Text));
                arrParams.Add(SqlHelper.CreateParameterObject("@Image", SqlDbType.NVarChar, ParameterDirection.Input, UploadFile(txtAnhSP)));
                arrParams.Add(SqlHelper.CreateParameterObject("@KM", SqlDbType.Int, ParameterDirection.Input, Convert.ToInt32(txtKhuyenMai.Text.Equals("") ? "0" : txtKhuyenMai.Text)));
                arrParams.Add(SqlHelper.CreateParameterObject("@Gia", SqlDbType.Float, ParameterDirection.Input, Convert.ToDouble(txtGiaSP.Text)));
                arrParams.Add(SqlHelper.CreateParameterObject("@IsNew", SqlDbType.Int, ParameterDirection.Input, rbtNew.Checked ? 1 : 0));
                arrParams.Add(SqlHelper.CreateParameterObject("@GhiChu", SqlDbType.NText, ParameterDirection.Input, txtGhiChu.Value));
                IDSanPham = Convert.ToInt32(SqlHelper.ExecuteScalar(CommandType.Text, sql, arrParams).ToString());
                ThemAnhSanPham(IDSanPham);
                ThemDacTinhSanPham(IDSanPham);
                Mytrans.Commit();
            }
            catch (Exception ex)
            {
                Response.Write(ex.StackTrace);
                Mytrans.Rollback();
            }
        }

        private void ThemAnhSanPham(int idenNumber)
        {
            string sql = "INSERT INTO dbo.tblT2BAnhSanPham(IDSanPham,Image,CreateDate)VALUES(@IDSanPham,@Image,GETDATE())";
            List<SqlParameter> arrParamsImage = new List<SqlParameter>();
            if (txtAnhSP1.HasFile)
            {
                arrParamsImage.Add(SqlHelper.CreateParameterObject("@IDSanPham", SqlDbType.Int, ParameterDirection.Input, idenNumber));
                arrParamsImage.Add(SqlHelper.CreateParameterObject("@Image", SqlDbType.NVarChar, ParameterDirection.Input, UploadFile(txtAnhSP1)));
                SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParamsImage);
                arrParamsImage.RemoveRange(0, arrParamsImage.Count);
            }
            if (txtAnhSP2.HasFile)
            {
                arrParamsImage.Add(SqlHelper.CreateParameterObject("@IDSanPham", SqlDbType.Int, ParameterDirection.Input, idenNumber));
                arrParamsImage.Add(SqlHelper.CreateParameterObject("@Image", SqlDbType.NVarChar, ParameterDirection.Input, UploadFile(txtAnhSP2)));
                SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParamsImage);
                arrParamsImage.RemoveRange(0, arrParamsImage.Count);
            }
            if (txtAnhSP3.HasFile)
            {
                arrParamsImage.Add(SqlHelper.CreateParameterObject("@IDSanPham", SqlDbType.Int, ParameterDirection.Input, idenNumber));
                arrParamsImage.Add(SqlHelper.CreateParameterObject("@Image", SqlDbType.NVarChar, ParameterDirection.Input, UploadFile(txtAnhSP3)));
                SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParamsImage);
                arrParamsImage.RemoveRange(0, arrParamsImage.Count);
            }
            if (txtAnhSP4.HasFile)
            {
                arrParamsImage.Add(SqlHelper.CreateParameterObject("@IDSanPham", SqlDbType.Int, ParameterDirection.Input, idenNumber));
                arrParamsImage.Add(SqlHelper.CreateParameterObject("@Image", SqlDbType.NVarChar, ParameterDirection.Input, UploadFile(txtAnhSP4)));
                SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParamsImage);
                arrParamsImage.RemoveRange(0, arrParamsImage.Count);
            }
            if (txtAnhSP5.HasFile)
            {
                arrParamsImage.Add(SqlHelper.CreateParameterObject("@IDSanPham", SqlDbType.Int, ParameterDirection.Input, idenNumber));
                arrParamsImage.Add(SqlHelper.CreateParameterObject("@Image", SqlDbType.NVarChar, ParameterDirection.Input, UploadFile(txtAnhSP5)));
                SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParamsImage);
                arrParamsImage.RemoveRange(0, arrParamsImage.Count);
            }
            
        }

        private void ThemDacTinhSanPham(int idenNumber)
        {

            string sql = "INSERT INTO dbo.tblT2BKhoHang(SanPhamID,SizeID_DM,ColorID_DM,Image,SL,CreateDate) " +
                        "VALUES(@SanPhamID,@SizeID_DM,@ColorID_DM,@Image,0,GETDATE())";
            List<SqlParameter> arrParams = new List<SqlParameter>();
            foreach (DataListItem li in dtlMauSac.Items)
            {
                CheckBox chkColor = (CheckBox)li.FindControl("chkColor");
                HiddenField hdnID = (HiddenField)li.FindControl("hdnID");
                CheckBoxList cbl = (CheckBoxList)li.FindControl("chkSizeList");
                FileUpload fulImage = (FileUpload)li.FindControl("fulImage");
                if (chkColor.Checked)
                {
                    string ImageUrl = UploadFile(fulImage);
                    foreach (ListItem item in cbl.Items)
                    {
                        if (item.Selected)
                        {
                            if (CheckDacTinhSanPham(Convert.ToInt32(hdnID.Value), Convert.ToInt32(item.Value), idenNumber))
                            {
                                arrParams.Add(SqlHelper.CreateParameterObject("@SanPhamID", SqlDbType.Int, ParameterDirection.Input, idenNumber));
                                arrParams.Add(SqlHelper.CreateParameterObject("@SizeID_DM", SqlDbType.Int, ParameterDirection.Input, item.Value));
                                arrParams.Add(SqlHelper.CreateParameterObject("@ColorID_DM", SqlDbType.Int, ParameterDirection.Input, hdnID.Value));
                                arrParams.Add(SqlHelper.CreateParameterObject("@Image", SqlDbType.NVarChar, ParameterDirection.Input, ImageUrl));
                                SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParams);
                                arrParams.Clear();
                            }
                        }
                    }
                }
            }
        }

        private bool CheckDacTinhSanPham(int color, int size, int IDSP)
        {
            string sql = "SELECT * FROM dbo.tblT2BKhoHang WHERE SizeID_DM = @SizeID_DM AND ColorID_DM = @ColorID_DM AND SanPhamID = @IDSP";
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@SizeID_DM", SqlDbType.Int, ParameterDirection.Input, size));
            arrParams.Add(SqlHelper.CreateParameterObject("@ColorID_DM", SqlDbType.Int, ParameterDirection.Input, color));
            arrParams.Add(SqlHelper.CreateParameterObject("@IDSP", SqlDbType.Int, ParameterDirection.Input, IDSP));
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql, arrParams);
            if (dt.Rows.Count == 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        protected void grvData_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string sID = e.CommandArgument.ToString().Trim();
            string sCommandName = e.CommandName;
            if (sCommandName == ThoiTrangT2B.MyConst.Action.Update)
            {
                Response.Redirect("CapNhatKhoHang.aspx?pID=" + sID);
            }
            if (sCommandName == ThoiTrangT2B.MyConst.Action.AddImage)
            {
                Response.Redirect("AnhSanPham.aspx?sID=" + sID);
            }
            if (sCommandName == ThoiTrangT2B.MyConst.Action.Approve)
            {
                btnLuu.CommandName = MyConst.Action.Approve;
                MultiView1.ActiveViewIndex = 0;
                LoadHangSP(cboHangSanXuat);
                LoadNhomSP();
                RowMauSac.Visible = false;
                LoadChiTietSanPham(Convert.ToInt32(sID));
                IDSanPham = Convert.ToInt32(sID);
            }
            if (sCommandName == MyConst.Action.Delete)
            {
                string sql = "SELECT Image FROM dbo.tblT2BSanPham WHERE ID = " + sID;
                string FileName = SqlHelper.ExecuteScalar(CommandType.Text, sql).ToString();
                sql = "DELETE FROM dbo.tblT2BSanPham WHERE ID = " + sID;
                SqlHelper.ExecuteNonQuery(CommandType.Text, sql);
                try
                {
                    File.Delete(Server.MapPath("../" + FileName));
                    DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, "SELECT * FROM dbo.tblT2BAnhSanPham WHERE IDSanPham = " + sID);
                    if (dt.Rows.Count > 0)
                    {
                        foreach (DataRow item in dt.Rows)
                        {
                            File.Delete(Server.MapPath("../" + item["Image"]));
                        }
                    }
                    SqlHelper.ExecuteNonQuery(CommandType.Text, "DELETE FROM dbo.tblT2BAnhSanPham WHERE IDSanPham = " + sID);
                    dt = null;
                    dt = SqlHelper.ExecuteDataTable(CommandType.Text, "SELECT * FROM dbo.tblT2BKhoHang WHERE SanPhamID = " + sID);
                    if (dt.Rows.Count > 0)
                    {
                        foreach (DataRow item in dt.Rows)
                        {
                            File.Delete(Server.MapPath("../" + item["Image"]));
                        }
                    }
                    SqlHelper.ExecuteNonQuery(CommandType.Text, "DELETE FROM dbo.tblT2BKhoHang WHERE SanPhamID = " + sID);
                }
                catch (Exception ex)
                {
                    Response.Write("Không có file ảnh");
                }
            }
            grvData.EditIndex = -1;
            LoadListSanPham();
        }

        private void LoadChiTietSanPham(int sID)
        {
            string sql = "SELECT * FROM dbo.tblT2BSanPham WHERE ID = " + sID;
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql);
            cboMenu.SelectedValue = dt.Rows[0]["Menu_ID"].ToString(); ;
            txtTenSP.Text = dt.Rows[0]["TenSP"].ToString();
            txtMaSP.Text = dt.Rows[0]["MaSP"].ToString();
            if (dt.Rows[0]["Image"] == DBNull.Value)
            {
                imgAnhSP.ImageUrl = "../images/no_image.jpg";
            }
            else
            {
                imgAnhSP.ImageUrl = "../" + dt.Rows[0]["Image"].ToString();
            }
            cboHangSanXuat.SelectedValue = (dt.Rows[0]["ThuongHieuID_DM"].ToString());
            txtGiaSP.Text = (Convert.ToDouble(dt.Rows[0]["Gia"]) - (Convert.ToDouble(dt.Rows[0]["Gia"]) * Convert.ToDouble(dt.Rows[0]["KM"]) / 100)).ToString();
            txtKhuyenMai.Text = dt.Rows[0]["KM"].ToString();
            txtGhiChu.Value = dt.Rows[0]["GhiChu"].ToString();
            sql = "SELECT * FROM dbo.tblT2BAnhSanPham WHERE IDSanPham = " + sID;
            DataTable dtImage = SqlHelper.ExecuteDataTable(CommandType.Text, sql);
            ltrImage.Text = "";
            foreach (DataRow item in dtImage.Rows)
            {
                ltrImage.Text += "<img src='../" + item["Image"] + "' style='width:80px;float:left' />";
            }
        }

        protected void grvData_RowEditing(object sender, GridViewEditEventArgs e)
        {
            grvData.EditIndex = e.NewEditIndex;
            LoadListSanPham();
        }

        protected void grvData_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            grvData.EditIndex = -1;
            LoadListSanPham();
        }

        protected void grvData_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            grvData.DeleteRow(e.RowIndex);
            grvData.DataBind();
        }

        protected void btnLuu_Click(object sender, EventArgs e)
        {
            if (btnLuu.CommandName == MyConst.Action.Addnew)
            {
                ThemSanPham();
            }
            else
            {
                SuaSanPham();
            }
            LoadListSanPham();
            MultiView1.ActiveViewIndex = 1;
        }

        protected void btnThemMoi_Click(object sender, EventArgs e)
        {
            btnLuu.CommandName = MyConst.Action.Addnew;
            MultiView1.ActiveViewIndex = 0;
            LoadHangSP(cboHangSanXuat);
            LoadNhomSP();
            RowMauSac.Visible = true;
            LoadColor();
            ClearField();
        }

        private void ClearField()
        {
            txtTenSP.Text = "";
            txtMaSP.Text = "";
            cboHangSanXuat.SelectedValue = "-1";
            txtGiaSP.Text = "";
            txtKhuyenMai.Text = "";
            txtGhiChu.Value = "";
            imgAnhSP.ImageUrl = "../images/no_image.jpg";
        }

        protected void LoadHangSP(DropDownList ddl)
        {
            string sql = "SELECT * FROM dbo.tblT2BDanhMuc WHERE MaDM = 'hang'";
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql);
            ddl.DataSource = dt;
            ddl.DataTextField = "TenDM";
            ddl.DataValueField = "ID";
            ddl.DataBind();
            ddl.Items.Insert(0, new ListItem("Chọn hãng sản xuất", "-1"));
        }
        protected void LoadNhomSP()
        {
            string sql = "SELECT * FROM dbo.tblT2BMenu";
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql);
            cboMenu.DataSource = dt;
            cboMenu.DataTextField = "Ten";
            cboMenu.DataValueField = "ID";
            cboMenu.DataBind();
            cboMenu.Items.Insert(0, new ListItem("Chọn nhóm danh mục hiển thị", "-1"));
        }

        protected void btnHuy_Click(object sender, EventArgs e)
        {
            ClearField();
            MultiView1.ActiveViewIndex = 1;
        }

        private string UploadFile(FileUpload ful)
        {
            try
            {
                if (ful.HasFile)
                {
                    string sFolderPath = Server.MapPath(@"../userfiles/product");
                    HttpPostedFile myFile = ful.PostedFile;
                    string sFileName = myFile.FileName;
                    string[] arrFileName = sFileName.Split('.');
                    arrFileName[0] = arrFileName[0] + "_" + DateTime.Now.ToString("ddMMyyhhssmm");
                    sFileName = arrFileName[0] + "." + arrFileName[1];

                    // Create a bitmap of the content of the fileUpload control in memory
                    Bitmap originalBMP = new Bitmap(ful.FileContent);

                    // Calculate the new image dimensions
                    float origWidth = originalBMP.Width;
                    float origHeight = originalBMP.Height;
                    float sngRatio;
                    if (origHeight > origWidth)
                    {
                        sngRatio = origHeight / origWidth;
                    }
                    else
                    {
                        sngRatio = origWidth / origHeight;
                    }
                    int newWidth = 650;
                    int newHeight = Convert.ToInt32(newWidth * sngRatio);

                    // Create a new bitmap which will hold the previous resized bitmap
                    Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);

                    // Create a graphic based on the new bitmap
                    Graphics oGraphics = Graphics.FromImage(newBMP);
                    // Set the properties for the new graphic file
                    oGraphics.SmoothingMode = SmoothingMode.AntiAlias; oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

                    // Draw the new graphic based on the resized bitmap
                    oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
                    // Save the new graphic file to the server
                    newBMP.Save(string.Format(@"{0}\{1}", sFolderPath, sFileName));

                    // Once finished with the bitmap objects, we deallocate them.
                    originalBMP.Dispose();
                    newBMP.Dispose();
                    oGraphics.Dispose();

                    //myFile.SaveAs(string.Format(@"{0}\{1}", sFolderPath, sFileName));
                    return "userfiles/product/" + sFileName;




                }
                else
                {
                    return "";
                }
            }
            catch (Exception)
            {
                return "";
            }
        }

        protected void grvData_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvData.PageIndex = e.NewPageIndex;
            grvData.DataBind();
        }

        protected void ddlHangSanXuat_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadListSanPham(Convert.ToInt32(ddlHangSanXuat.SelectedValue));
        }

        protected void dtlMauSac_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                CheckBoxList cbl = (CheckBoxList)e.Item.FindControl("chkSizeList");
                string sql = "SELECT * FROM dbo.tblT2BDanhMuc WHERE MaDM = 'size'";
                DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    cbl.Items.Add(new ListItem("Size " + dt.Rows[i]["TenDM"].ToString(), dt.Rows[i]["ID"].ToString()));
                }
            }
        }
    }
}
